package com.levi.juc.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 异步回调
 * 1.CompletableFuture.runAsync  没有返回值
 * 2.CompletableFuture.supplyAsync  有返回
 */
public class CompletableFutureTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //没有返回值的 CompletableFuture
 /*       CompletableFuture<Void> future =  CompletableFuture.runAsync(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+">>>runAsync");
        });
        //先执行1111111
        System.out.println("111111");
        //会阻塞，等待2秒执行完之后再get
        future.get();*/


        //有返回值的 CompletableFuture
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            int a = 1 / 0;  //出现异常这时候执行   exceptionally
            return 1024;
        });
        //当成功的时候执行t  ，当失败的时候执行u
        future.whenComplete((t, u) -> {
            System.out.println("t>>>>>" + t);
            System.out.println("u>>>>>" + u);
            //出现异常的时候执行exceptionally
        }).exceptionally((e) -> {
            System.out.println(e.getMessage());
            return 233;
        }).get();
    }
}
